<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :title="getTitle" @ok="handleSubmit">
    <div class="">
      <div class="p-2 text-right">
        <a-button type="primary" @click="handleAdd" size="small">新增</a-button>
      </div>
      <Table :dataSource="list" :columns="columns" :pagination="false" :customRow="customRow">
      <template #move>
        &#9769
      </template>
        <template #tztj="{ record, index }">
          <div class="flex">
            <Select
              :options="firstBracketOptions"
              v-model:value="record['firstBracket']"
              class="w-80px"
              style="margin-right: 5px"
              :get-popup-container="getPopupContainer"
            />

            <Select
              :options="formGetFieldsData"
              v-model:value="record['fieldName']"
              class="w-200px"
              style="margin-right: 5px"
              optionFilterProp="label"
              showSearch
              @change="handleFieldNameChange($event, record)"
              :get-popup-container="getPopupContainer"
            />
            <Select
              :options="compareOptions"
              v-model:value="record['compare']"
              class="w-100px"
              style="margin-right: 5px"
              :get-popup-container="getPopupContainer"
            />
            <Select
              :options="columnNameOptions1"
              v-model:value="record['columnName']"
              class="w-100px"
              style="margin-right: 5px"
              v-if="record['fieldNameType'] == 'cws_status'"
              :get-popup-container="getPopupContainer"
            />
            <Select
              :options="columnNameOptions2"
              v-model:value="record['columnName']"
              class="w-100px"
              style="margin-right: 5px"
              v-if="record['fieldNameType'] == 'cws_flag'"
              :get-popup-container="getPopupContainer"
            />
            <Select
              :options="formGetFieldsMainData"
              v-model:value="record['columnName']"
              class="w-200px"
              style="margin-right: 5px"
              optionFilterProp="label"
              showSearch
              v-if="record['fieldNameType'] == 'mainFormOpt'"
              :get-popup-container="getPopupContainer"
            />

            <div
              class="w-150px"
              style="margin-right: 5px"
              v-if="
                record['fieldNameType'] != 'cws_status' &&
                record['fieldNameType'] != 'cws_flag' &&
                record['fieldNameType'] != 'mainFormOpt'
              "
            >
              <FormCtl
                v-if="
                  record['fieldNameType'] &&
                  record['fieldNameType'].indexOf('{$}') == -1 &&
                  record['formCode']
                "
                :formCode="record['formCode']"
                :fieldName="record['fieldNameType']"
                v-model:value="record['columnName']"
                style="width: 100px; margin-right: 5px"
              />
              <Input v-else v-model:value="record['columnName']" />
            </div>

            <div class="w-120px flex items-center">
              <Dropdown :get-popup-container="getPopupContainer">
                <span> {{ record['columnNameTitle'] }} <DownOutlined /> </span>
                <template #overlay>
                  <Menu @click="({ key }) => handleClickMenu(key, record)">
                    <MenuItem :key="k.value" v-for="k in dropdownMenuOptions">
                      {{ k.label }}
                    </MenuItem>
                  </Menu>
                </template>
              </Dropdown>
            </div>
            <Select
              :options="firstBracketOptions"
              v-model:value="record['twoBracket']"
              class="w-80px"
              style="margin-right: 5px"
              :get-popup-container="getPopupContainer"
            />
            <Select
              :options="logicalOptions"
              v-model:value="record['logical']"
              class="w-80px"
              style="margin-right: 5px"
              v-if="index != list.length - 1"
              :get-popup-container="getPopupContainer"
            />
          </div>
        </template>
        <template #action="{ index }">
          <div class="flex">
            <!-- <a-button type="primary" class="mr-2" size="small" @click="handleAdd">新增</a-button> -->
            <a-button type="primary" size="small" @click="handleDelete(index)">删除</a-button>
          </div>
        </template>
      </Table>
    </div>
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref, computed, unref, onMounted, reactive } from 'vue';
  import { Input, Table, Select, Dropdown, Menu } from 'ant-design-vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { DownOutlined } from '@ant-design/icons-vue';
  import { FormCtl } from '/@/components/FormCtl';
  import {
    firstBracketOptions,
    columns,
    logicalOptions,
    compareOptions,
    compareOptions2,
    compareOptions3,
    fieldNameOptions,
    columnNameOptions1,
    columnNameOptions2,
    dropdownMenuOptions,
  } from './nestTableFormConfigationModal.data';
  import { getFormGetFields } from '/@/api/flowManage/flowManage';
  import { useRouter } from 'vue-router';
  import { isArray } from '/@/utils/is';

  export default defineComponent({
    name: 'NestTableFormConfigationModal',
    components: {
      BasicModal,
      Table,
      Select,
      Input,
      DownOutlined,
      Dropdown,
      Menu,
      MenuItem: Menu.Item,
      FormCtl,
    },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const { currentRoute } = useRouter();
      const dataRef = ref<Recordable>({});
      const formData = ref<Recordable>({});
      const list = ref<any>([]);
      const getTitle = '配置';
      const formGetFieldsData = ref<Recordable>([]);
      const { createMessage } = useMessage();

      const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
        setModalProps({ confirmLoading: false, width: '80%', zIndex: 2000 });
        try {
          console.log('data', data);
          formGetFieldsData.value = fieldNameOptions;
          if (data?.formGetFieldsData) {
            const newFormGetFieldsData = data.formGetFieldsData.map((item) => {
              return {
                value: item.name,
                label: item.title,
                formCode: item.formCode,
              };
            });
            formGetFieldsData.value = [...newFormGetFieldsData, ...fieldNameOptions];
          }
          if (data?.list) {
            list.value = JSON.parse(JSON.stringify(data.list));
          }
        } catch (err) {
          console.log(err);
        }
      });

      async function handleSubmit() {
        try {
          setModalProps({ confirmLoading: true });

          formData.value = Object.assign({}, dataRef.value);
          let isValid = true;
          list.value.forEach((item) => {
            for (let v in item) {
              if (item[v] == null || item[v] == 'null') {
                item[v] == '';
              }
              if (item.compare == '') {
                isValid = false;
              }
            }
          });

          if (!isValid) {
            createMessage.warn('请选择判断符号');
            return;
          }

          console.log('list', list.value);
          closeModal();
          emit('success', unref(list));
        } catch (err) {
          console.log(err);
        } finally {
          setModalProps({ confirmLoading: false });
        }
      }

      const handleAdd = () => {
        // list.value.push({
        //   columnName: '',
        //   compare: '',
        //   firstBracket: '',
        //   value: '',
        //   twoBracket: '',
        //   logical: 'and',
        //   columnNameTitle: '',
        // });

        list.value.push({
          columnName: '',
          compare: '',
          firstBracket: '',
          value: '',
          twoBracket: '',
          logical: 'and',
          columnNameTitle: '',
          fieldName:
            isArray(formGetFieldsData.value) && formGetFieldsData.value.length
              ? formGetFieldsData.value[0].value
              : '',
        });

        list.value = [...list.value];
        console.log('list.value', list.value);
      };
      const handleDelete = (index) => {
        list.value.splice(index, 1);
        list.value = [...list.value];
      };

      const handleFieldNameChange = (val, record) => {
        record['columnName'] = '';
        record['columnNameTitle'] = '';
        record['fieldNameType'] = val;
        record['formCode'] = formGetFieldsData.value.find((item) => item.value == val)?.formCode;
        console.log(
          'handleFieldNameChange record',
          record,
          'formGetFieldsData',
          formGetFieldsData.value,
        );
      };

      const formGetFieldsMainData = ref<Recordable[]>([]);
      //获取主表字段
      const getFormGetFieldsMainData = () => {
        try {
          const { query } = currentRoute.value;
          if (query?.formCode) {
            getFormGetFields({ formCode: query.formCode }).then((res) => {
              formGetFieldsMainData.value = res || [];
              if (isArray(formGetFieldsMainData.value)) {
                formGetFieldsMainData.value.forEach((item) => {
                  item.value = '{$' + item.name + '}';
                  item.label = item.title;
                  delete item.options;
                });
              }
            });
          }
        } catch (err) {
          console.log('getFormGetFieldsMainData', err);
        }
      };
      onMounted(() => {
        getFormGetFieldsMainData();
      });

      //点击菜单
      const handleClickMenu = (key, record) => {
        console.log('key', key);
        record['fieldNameType'] = key;
        if (key === 'mainFormOpt') {
          record['columnName'] = formGetFieldsMainData.value[0]?.value;
        } else {
          record['columnName'] = key;
        }
        const obj2 = dropdownMenuOptions.find((k) => k.value == key);
        if (obj2) {
          // 如果不是主表字段，则置formCode为空，否则会被视为FormCtl
          if (key !== 'mainFormOpt') {
            record['formCode'] = '';
          }
          record['columnNameTitle'] = obj2?.label;
        }
        console.log('handleClickMenu', record);
      };

      const getPopupContainer = (triggerNode) => triggerNode?.parentNode;

      let source = 0; // 源目标数据序号
      let target = 0; // 目标数据序号
      // Table行拖拽
      function customRow(record, index) {
        return {
          props: {
            // draggable: 'true'
          },
          style: {
            // cursor: 'pointer',
          },
          // 鼠标移入
          onMouseenter: (event) => {
            // event.srcElement.tagName始终为TR，无法区分是点在了哪一列
          },
          onMousedown: (event) => {
            console.log('event', event);
            event.stopPropagation();
            console.log('event', event.srcElement.tagName);
            if (event.srcElement.tagName === 'TD') {
              let cellIndex = event.srcElement.cellIndex;
              console.log('cellIndex', cellIndex);
              // 如果点击的是第1列（第0列为复选框列），则使可以拖动
              // 因拖拽会影响拷贝粘贴，故限制只能在第1列可拖拽
              if (cellIndex == 0) {
                event.target.draggable = true; // 使可以拖动
              }
            }
          },
          // 开始拖拽
          onDragstart: (event) => {
            // 兼容IE
            let ev = event || window.event;
            // 阻止冒泡
            ev.stopPropagation();
            // 得到源目标数据序号
            source = index;
            console.log(record, index, 'source');
          },
          // 拖动元素经过的元素
          onDragover: (event) => {
            // 兼容 IE
            let ev = event || window.event;
            // 阻止默认行为
            ev.preventDefault();
          },
          // 鼠标松开
          onDrop: (event) => {
            // 兼容IE
            let ev = event || window.event;
            // 阻止冒泡
            ev.stopPropagation();
            // 得到目标数据序号
            target = index;
            const dataFrom = list.value[source];
            list.value.splice(source, 1);
            list.value.splice(target, 0, dataFrom);
            // event.target.parentElement.draggable = false; // 取消拖动
            // console.log(record, index, 'target', source, target);
          },
          onDblclick: () => {},
          onClick: (ev) => {
            console.log('onClick', ev);
            ev.stopPropagation();
          },
        };
      }
      return {
        registerModal,
        getTitle,
        handleSubmit,
        list,
        columns,
        firstBracketOptions,
        formGetFieldsData,
        logicalOptions,
        compareOptions2,
        handleAdd,
        handleDelete,
        compareOptions,
        compareOptions3,
        columnNameOptions1,
        columnNameOptions2,
        dropdownMenuOptions,
        handleClickMenu,
        handleFieldNameChange,
        formGetFieldsMainData,
        getPopupContainer,
        customRow,
      };
    },
  });
</script>
